package com.file.system.tools.rand;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.RandomUtil;
import com.file.system.plugin.shiro.ShiroTools;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description （生成随机验证码）
 * @Author jch
 * @Date 2017/5/2 11:23
 */
@Component
@Configuration
public class RandCheckCode {

    Logger logger = LogManager.getLogger(RandCheckCode.class);


    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void buildCheckCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 生产验证码字符串并保存到session中
            AbstractCaptcha captcha = getCaptcha();
            String randCheckCode = captcha.getCode();
            logger.info(randCheckCode);

            ShiroTools.getSession().setAttribute("randCheckCode", randCheckCode);

            // 将验证码图片写入响应流
            captcha.write(response.getOutputStream());

            // 设置响应头信息
            response.setHeader("Cache-Control", "no-store, no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            // 刷新响应流并关闭
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取验证码
     */
    private AbstractCaptcha getCaptcha() {
        int num = RandomUtil.randomInt(1, 4);
        // 验证码宽、高、个数
        int width = 310, height = 120, codeCount = 4;

        AbstractCaptcha captcha;
        switch (num) {
            case 1:
                // 圆圈验证码
                captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, 20);
                break;
            case 2:
                // 扭曲验证码
                captcha = CaptchaUtil.createShearCaptcha(width, height, codeCount, 4);
                break;
            case 3:
                // 线段验证码
                captcha = CaptchaUtil.createLineCaptcha(width, height, codeCount, 30);
                break;
            default:
                // 圆圈验证码
                captcha = CaptchaUtil.createCircleCaptcha(width, height, codeCount, 20);
                break;
        }

        return captcha;
    }

}
